<?php
/*
 * 数据库工厂
 */

namespace Yjius\libraries;

use Yii;

final class DbFactory
{

    private static $instance = [];

    private function __construct($dbName)
    {
        try {
            $configFile = Yii::getAlias('@common/config/db/' . $dbName . '.php');
            if (!file_exists($configFile)) {
                throw new \Exception('配置文件不存在：' . $dbName);
            }
        } catch (\Exception $e) {
            throw new \Exception('不合法的路径：' . $dbName . '，Error：' . $e->getMessage());
        }
        try {
            $config = require $configFile;
            $class = $config['class'];
            unset($config['class']);
            self::$instance[$dbName] = new $class($config);
        } catch (\Exception $e) {
            throw new \Exception('实例化错误：Error：' . $e->getMessage());
        }
    }

    private function __clone()
    {
        throw new \Exception('单例模式，禁止克隆');
    }

    /**
     * 获取数据库实例
     * @param string $dbName 数据库配置文件名
     * @return \yii\db\Connection 数据库实例
     */
    public static function getInstance($dbName)
    {
        if (!isset(self::$instance[$dbName])) {
            new self($dbName);
        }
        return self::$instance[$dbName];
    }

}

